package cn.woochen.functionwidget.widget

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Context.WINDOW_SERVICE
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.SystemClock
import android.provider.Settings
import android.text.Html
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import cn.woochen.functionwidget.R
import cn.woochen.functionwidget.sample.SdkActivity
import cn.woochen.functionwidget.sample.util.PackageUtil
import cn.woochen.functionwidget.sample.util.UrlConstainer


/**
 *悬浮窗
 *@author woochen
 *@time 2019/4/24 13:57
 */
@SuppressLint("StaticFieldLeak")
object FloatView : View.OnTouchListener, View.OnClickListener {

    var isShowing = false
    private var x: Int = 0
    private var y: Int = 0
    private var mView: View? = null
    private lateinit var windowManager: WindowManager
    private lateinit var layoutParams: WindowManager.LayoutParams
    private var downMillionTime = 0L
    private var isDialogShow: Boolean = false

    fun createView(context: Context) {
        if (isShowing) return
        mView = View.inflate(context, R.layout.view_float, null)
        mView?.post {
            initView(context)
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(context)) {
                    //若没有权限，提示获取.
                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                    Toast.makeText(context, "需要取得权限以使用悬浮窗", Toast.LENGTH_SHORT).show()
                    PackageUtil.currentActivity?.startActivityForResult(intent, 100)
                }
            }
        }
        windowManager = context.applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
        layoutParams = WindowManager.LayoutParams()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE
        }
        layoutParams.format = PixelFormat.RGBA_8888
        layoutParams.gravity = Gravity.LEFT or Gravity.TOP
        layoutParams.flags =
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        layoutParams.x = 100
        layoutParams.y = 100
        windowManager.addView(mView, layoutParams)
        mView?.setOnTouchListener(this)
        mView?.setOnClickListener(this)
        isShowing = true

    }

    private var tvState: TextView? = null
    private var tvVersion: TextView? = null

    private fun initView(context: Context) {
        tvState = mView?.findViewById(R.id.tv_state)
        tvVersion = mView?.findViewById(R.id.tv_version)
        tvState?.text = checkEnvironment()
        tvVersion?.text = PackageUtil.getCurrentVersionName(context)

    }

    private fun checkEnvironment(): String = when (UrlConstainer.appBaseUrl) {
        UrlConstainer.APP_RELEASE_URL -> {
            mView?.background = mView?.context?.resources?.getDrawable(R.drawable.shape_circle_green)
            "线上"
        }
        else -> {
            mView?.background = mView?.context?.resources?.getDrawable(R.drawable.shape_circle_yellow)
            UrlConstainer.appBaseUrl = UrlConstainer.APP_TEST_URL
            "测试"
        }

    }


    /**
     * 重新登录
     */
    private fun reLogin() {
        //需要清除登录状态

        Toast.makeText(mView?.context, "运行环境切换成功，请重新登录！",Toast.LENGTH_SHORT).show()
        val currentActivity = PackageUtil.currentActivity
        if (currentActivity!=null && currentActivity !is SdkActivity) {
            val intent = Intent(currentActivity, SdkActivity::class.java)
            currentActivity.startActivity(intent)
        }
    }


    fun dismiss() {
        if (!isShowing) return
        if (mView != null) {
            windowManager.removeViewImmediate(mView)
            isShowing = false
            mView = null
        }
    }


    override fun onClick(v: View?) {
        exchangeEnvironment()
    }


    private fun exchangeEnvironment() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            AlertDialog.Builder(PackageUtil.currentActivity)
                    .setMessage(Html.fromHtml("当前处于<font color='#ff0000'>${checkEnvironment()}</font>环境，您确定要切换吗？"))
                    .setPositiveButton("确定") { _, _ ->
                        UrlConstainer.appBaseUrl = when (UrlConstainer.appBaseUrl) {
                            UrlConstainer.APP_RELEASE_URL -> UrlConstainer.APP_TEST_URL
                            else -> UrlConstainer.APP_RELEASE_URL
                        }
                        tvState?.text = checkEnvironment()
                        reLogin()
                    }
                    .setNegativeButton("取消", null)
                    .setOnDismissListener {
                        isDialogShow = false
                        mView?.isEnabled = !isDialogShow
                    }
                    .show()
        }
        isDialogShow = true
        mView?.isEnabled = !isDialogShow
    }

    override fun onTouch(view: View?, event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                downMillionTime = SystemClock.uptimeMillis()
                x = event.rawX.toInt()
                y = event.rawY.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                val nowX = event.rawX.toInt()
                val nowY = event.rawY.toInt()
                val movedX = nowX - x
                val movedY = nowY - y
                x = nowX
                y = nowY
                layoutParams.x = layoutParams.x + movedX
                layoutParams.y = layoutParams.y + movedY
                Log.e("eee", "currentX->${layoutParams.x} currentY->${layoutParams.y}")
                windowManager.updateViewLayout(view, layoutParams)
            }
            MotionEvent.ACTION_UP -> {
                Log.e("eee", "操作时长->${(SystemClock.uptimeMillis() - downMillionTime)}  ${SystemClock.uptimeMillis()}  $downMillionTime")
                return (SystemClock.uptimeMillis() - downMillionTime) > 150
            }
        }
        return false
    }


}